package folder.model.network;

import java.util.List;

import folder.model.link.Link;
import folder.model.link.LinkAllocation;
import folder.model.node.NodeAllocation;
import folder.model.virtual.VirtualLink;
import folder.model.virtual.VirtualNetwork;
import folder.model.virtual.VirtualNode;

public class NetworkAllocation
{	
	public final NodeAllocation nodeAllocation;
	public final LinkAllocation linkAllocation;
	
	private Network network;
	
	public static NetworkAllocation networkAllocation( Network network )
	{
		return new NetworkAllocation( network );
	}
	
	public NetworkAllocation( Network network )
	{
		this.network = network;
		this.nodeAllocation = new NodeAllocation( network.getNodes() );
		this.linkAllocation = new LinkAllocation( network );		
	}
	
	public boolean allocate( VirtualNetwork virtualNetwork )
	{
		List< VirtualNode > virtualNodes = virtualNetwork.getVirtualNodes();
		nodeAllocation.run( virtualNodes );
						
		List< VirtualLink > virtualLinks = virtualNetwork.getVirtualLinks();
		
		boolean checkLinkAllocation = linkAllocation.allocateVirtualLinks( virtualLinks );
				
		if( !checkLinkAllocation )
		{
			virtualNetwork.release();
			this.checkBandwidthAvailable();
			
			return false;
		}
		
		this.checkBandwidthAvailable();
		
		return true;
	}
	
	public void release( VirtualNetwork virtualNetwork )
	{
		virtualNetwork.release();
		this.checkBandwidthAvailable();
	}
	
	private void checkBandwidthAvailable()
	{
		for( Link link: network.getLinks() )
			if( link.getBandwidthAvailable() == 0 )
				link.disconnect();
			else
				link.connect();
	}

}
